package com.yifeng.repo.micro.service.server.engine.dal.ds;

import com.baomidou.dynamic.datasource.aop.DynamicDataSourceAnnotationInterceptor;
import com.baomidou.dynamic.datasource.processor.DsProcessor;
import com.yifeng.repo.micro.service.server.engine.dal.TransactionTargetManager;
import org.aopalliance.intercept.MethodInvocation;

/**
 * Created by daibing on 2023/9/5.
 */
public class ForceDynamicDataSourceAnnotationInterceptor extends DynamicDataSourceAnnotationInterceptor {
    private static final String MASTER = "master";

    public ForceDynamicDataSourceAnnotationInterceptor(Boolean allowedPublicOnly, DsProcessor dsProcessor) {
        super(allowedPublicOnly, dsProcessor);
    }

    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable {
        // master方法直接走主库，不再切换数据源
        String methodName = invocation.getMethod().getName();
        if (methodName.startsWith(MASTER)) {
            return invocation.proceed();
        }

        // 写事务走主库，不再切换数据源
        Class<?> clazz = invocation.getMethod().getDeclaringClass();
        String target = clazz.getName() + "." + methodName;
        boolean writeMethod = TransactionTargetManager.containsWriteMethod(target, true);
        if (writeMethod) {
            return invocation.proceed();
        }

        // 非master的读事务，支持切换数据源，继续动态数据源的AOP切换逻辑
        return super.invoke(invocation);
    }
}
